package com.lin.cloud.disk.manage.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.lin.cloud.disk.common.entity.request.AccountRequestDTO;
import com.lin.cloud.disk.common.enums.EDeleteStatus;
import com.lin.cloud.disk.common.exception.BusinessException;
import com.lin.cloud.disk.entity.pojo.*;
import com.lin.cloud.disk.entity.request.*;
import com.lin.cloud.disk.entity.request.department.*;
import com.lin.cloud.disk.entity.response.PermissionGroupListResponse;
import com.lin.cloud.disk.entity.response.UserInfoResponse;
import com.lin.cloud.disk.service.*;
import com.lin.cloud.disk.manage.IDepartmentManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @program: blog
 * @description: DepartmentManageServiceImpl
 * @author: Lin
 * @create: 2020-12-10 22:14
 **/
@Slf4j
@Service
public class DepartmentManageServiceImpl implements IDepartmentManageService {

    @Resource
    private IDepartmentService departmentService;

    @Resource
    private IUserDepartmentService userDepartmentService;

    @Resource
    private IDepartmentPermissionService departmentPermissionService;

    @Resource
    private IPermissionService permissionService;

    @Resource
    private ICompanyDepartmentService companyDepartmentService;

    @Resource
    private IUserService userService;

    /**
     * 通过用户ID获取权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<Department> getDepartmentByUserId(Long userId) {
        List<Long> departmentIdList = userDepartmentService.selectDepartmentIdListByUserId(userId);
        if (CollectionUtil.isNotEmpty(departmentIdList)) {
            List<Department> departmentList = departmentService.selectDepartmentByDepartmentIdList(departmentIdList);
            if (CollectionUtil.isNotEmpty(departmentList)) {
                return departmentList;
            }
        }
        return Collections.emptyList();
    }

    /**
     * 获取部门权限列表
     *
     * @param request
     * @return
     */
    @Override
    public PermissionGroupListResponse getDepartmentPermissionList(GetDepartmentPermissionRequest request) {
        Long departmentId = request.getDepartmentId();
        List<Long> permissionIdList = departmentPermissionService.selectPermissionIdListByDepartmentIdList(Arrays.asList(departmentId));
        if (CollectionUtil.isNotEmpty(permissionIdList)) {
            List<Permission> permissionList = permissionService.selectPermissionListByPermissionIdList(permissionIdList);
            return new PermissionGroupListResponse(permissionList);
        }
        return null;
    }

    /**
     * 创建公司部门
     *
     * @param request
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createCompanyDepartment(CreateDepartmentRequest request) {
        // 创建部门
        Long departmentId = departmentService.createCompanyDepartment(request);
        // 添加到companyDepartment中
        CompanyDepartment companyDepartment = new CompanyDepartment();
        companyDepartment.setCompanyId(request.getUserDTO().getCompanyId());
        companyDepartment.setDepartmentId(departmentId);
        companyDepartment.setCreateBy(request.getUserDTO().getUsername());
        companyDepartment.setCreateTime(new Date());
        companyDepartmentService.createCompanyDepartment(companyDepartment);
    }


    /**
     * 删除公司部门
     *
     * @param request
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCompanyDepartment(DeleteDepartmentRequest request) {
        departmentService.deleteCompanyDepartment(request);
        companyDepartmentService.deleteCompanyDepartment(request);
    }


    /**
     * 修改公司部门
     *
     * @param request
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCompanyDepartment(UpdateDepartmentRequest request) {
        // 三者都为空则抛异常
        if (StringUtils.isBlank(request.getDepartmentName())
                && StringUtils.isBlank(request.getDepartmentDesc())
                && null == request.getParentId()
        ) {
            throw new BusinessException("修改公司部门错误，请检查参数是否有误！");
        }

        // 更新公司部门信息
        departmentService.updateCompanyDepartment(request);
        // 更新公司部门关联表信息
        companyDepartmentService.updateCompanyDepartment(request);

    }


    /**
     * 获取部门内部用户
     *
     * @param request
     * @return
     */
    @Override
    public List<UserInfoResponse> getDepartmentInnerUser(GetDepartmentUserRequest request) {
        // 检查部门是否存在或者正确
        Boolean isExist = companyDepartmentService.companyIsExistDepartment(request.getUserDTO().getCompanyId(), request.getDepartmentId());
        // 如果不存在 抛异常
        if (!isExist) {
            throw new BusinessException("部门不存在，请检查!");
        }
        // 存在 获取该用户
        List<Long> userIdList = userDepartmentService.selectUserIdListByDepartmentIdList(Arrays.asList(request.getDepartmentId()));
        if (CollectionUtils.isEmpty(userIdList)) {
            return Collections.EMPTY_LIST;
        }
        // 获取用户列表
        List<UserInfoResponse> userInfoResponseList = userService.getDepartmentUserInfoByUserIdList(userIdList);
        if (CollectionUtils.isEmpty(userInfoResponseList)) {
            return Collections.EMPTY_LIST;
        }
        return userInfoResponseList;
    }

    /**
     * 获取未分配部门的用户
     *
     * @param accountRequestDTO
     * @return
     */
    @Override
    public List<UserInfoResponse> getUnAllocationDepartmentUser(AccountRequestDTO accountRequestDTO) {
        List<Long> departmentIdList = companyDepartmentService.getDepartmentIdListByCompany(accountRequestDTO.getUserDTO().getCompanyId());
        // 没有部门 返回空数组
        if (CollectionUtils.isEmpty(departmentIdList)) {
            return Collections.EMPTY_LIST;
        }
        // 通过部门列表查询用户列表
        List<Long> userIdListByDepartmentIdList = userDepartmentService.selectUserIdListByDepartmentIdList(departmentIdList);
        // 获取公司内所有的用户ID
        List<Long> companyUserIdList = userService.findUserIdListByCompanyId(accountRequestDTO.getUserDTO().getCompanyId());
        // 取差集
        companyUserIdList.removeAll(userIdListByDepartmentIdList);
        if (CollectionUtils.isEmpty(companyUserIdList)){
            return Collections.EMPTY_LIST;
        }
        // 获取用户列表
        List<UserInfoResponse> userInfoResponseList = userService.getDepartmentUserInfoUserIdList(companyUserIdList,accountRequestDTO.getUserDTO().getCompanyId());
        if (CollectionUtils.isEmpty(userInfoResponseList)) {
            return Collections.EMPTY_LIST;
        }
        return userInfoResponseList;
    }

    /**
     * 分配/取消分配用户到指定部门
     *
     * @param request
     */
    @Override
        public void allocationUserToDepartment(AllocationUserToDepartmentRequest request) {
        List<Long> allocationUserList = request.getAllocationUserList() != null ? request.getAllocationUserList() :Collections.EMPTY_LIST;
        List<Long> unAllocationUserList = request.getUnAllocationUserList()!= null ? request.getUnAllocationUserList() :Collections.EMPTY_LIST;
        //  两者都不存在 在抛异常
        if (CollectionUtils.isEmpty(allocationUserList) && CollectionUtils.isEmpty(unAllocationUserList)) {
            throw new BusinessException("未选择分配/取消分配的用户,请重新选择");
        }
        List<Long> coverAuthorizationPartList = new ArrayList<>(allocationUserList.size());
        // 交集部分
        coverAuthorizationPartList.retainAll(unAllocationUserList);
        // 计算需要分配的部分
        allocationUserList.removeAll(coverAuthorizationPartList);
        // 不算需要取消分配的部分
        unAllocationUserList.removeAll(coverAuthorizationPartList);
        UserDepartment userDepartment = null;
        // 批量添加授权
        if (CollectionUtil.isNotEmpty(allocationUserList)) {
            List<UserDepartment> userDepartmentList = new ArrayList<>(allocationUserList.size());
            for (Long userId : allocationUserList) {
                userDepartment = new UserDepartment();
                userDepartment.setUserId(userId);
                userDepartment.setDepartmentId(request.getDepartmentId());
                userDepartment.setIsDelete(EDeleteStatus.UN_DELETE.getStatus());
                userDepartment.setCreateTime(new Date());
                userDepartment.setCreateBy(request.getUserDTO().getUsername());
                userDepartmentList.add(userDepartment);
            }
            // 添加到数据库
            userDepartmentService.batchInsertUserDepartment(userDepartmentList);
        }
        // 批量取消授权
        if (CollectionUtil.isNotEmpty(unAllocationUserList)){
            userDepartmentService.batchRemoveUserDepartment(request.getDepartmentId(),unAllocationUserList);
        }
    }
}
